﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Metadata.BarElement;
using Kingdee.BOS.Orm.DataEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.Tools
{
    public class BomExplorer
    {
        // 入口方法
        public DynamicObjectCollection ExploreBom(int newValue, Context ctx)
        {
            DynamicObjectCollection result = new DynamicObjectCollection();
            TraverseBom(newValue, result, ctx);
            return result;
        }

        // 递归核心方法
        private void TraverseBom(int newValue, DynamicObjectCollection result, Context ctx)
        {
            DynamicObjectCollection bomList = GetBomItems(newValue, ctx);
            var bom1 = bomList.Where(w => Convert.ToInt32(w["FERPCLSID"]) == 1);
            foreach (var bom in bom1)
            {
                result.Add(bom);
            }
            var bom2 = bomList.Where(w => Convert.ToInt32(w["FERPCLSID"]) == 2);

            // 递归终止条件：到达叶子节点（原材料）
            if (bom2.Count() <= 0) { return; }

            // 遍历子节点
            foreach (var child in bom2)
            {
                int newBomid = Convert.ToInt32(child["FMATERIALID"]);
                TraverseBom(newBomid, result, ctx);
            }

        }
        private DynamicObjectCollection GetBomItems(int newValue, Context ctx)
        {
            string bomVer = GetBomVer(newValue, ctx);
            string sql = string.Format(@"/*dialect*/ 
            SELECT T1.FMATERIALID,T1.FNUMERATOR/T1.FDENOMINATOR YL,CASE WHEN T1.FMATERIALTYPE=1 THEN '标准件'  WHEN T1.FMATERIALTYPE=2 THEN '返还件' ELSE '替代件' END FMATERIALTYPE,T2.FERPCLSID
            FROM T_ENG_BOM T0
            JOIN T_ENG_BOMCHILD T1 ON T1.FID=T0.FID
            JOIN t_BD_MaterialBase T2 ON T2.FMATERIALID=T1.FMATERIALID
            WHERE T1.FMATERIALTYPE<>3 and T0.FMATERIALID={0} AND T0.FNUMBER='{1}' ", newValue, bomVer);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(ctx, sql);
            return doc;
        }

        private string GetBomVer(int newValue, Context ctx)
        {
            string sql = string.Format(@"/*dialect*/ 
            select FNUMBER from T_ENG_BOM where FMATERIALID={0} ORDER BY FCREATEDATE DESC ", newValue);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(ctx, sql);
            if (doc != null && doc.Count > 0)
            {
                return doc.FirstOrDefault()[0].ToString();
            }
            return "";
        }
    }
}
